package com.medical.captcha.config;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import com.medical.captcha.config.properties.CaptchaProperties;
import com.medical.captcha.enums.CaptchaCodeTypeEnum;
import com.medical.captcha.service.CaptchaService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.awt.*;


/**
 * 验证吗相关配置
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
@EnableConfigurationProperties({CaptchaProperties.class})
public class CaptchaConfig {

    private final CaptchaProperties captchaProperties;

    /**
     * 验证码生成器
     * @return
     */
    @Bean
    public CodeGenerator codeGenerator() {
        String codeType = captchaProperties.getCode().getType();
        int codeLength = captchaProperties.getCode().getLength();
        if (CaptchaCodeTypeEnum.MATH.name().equalsIgnoreCase(codeType)) {
            // 数学公式验证码
            return new MathGenerator(codeLength);
        } else if (CaptchaCodeTypeEnum.RANDOM.name().equalsIgnoreCase(codeType)) {
            // 随机字符验证码
            return new RandomGenerator(codeLength);
        } else {
            throw new IllegalArgumentException("Invalid captcha generator type: " + codeType);
        }
    }

    /**
     * 验证码字体
     * @return
     */
    @Bean
    public Font captchaFont() {
        String fontName = captchaProperties.getFont().getName();
        int fontSize = captchaProperties.getFont().getSize();
        int fontWight = captchaProperties.getFont().getWeight();
        return new Font(fontName, fontWight, fontSize);
    }

    @Bean
    @ConditionalOnMissingBean
    public CaptchaService captchaService(CaptchaProperties captchaProperties, CodeGenerator codeGenerator, Font captchaFont) {
        CaptchaService captchaService = new CaptchaService();
        captchaService.setCaptchaProperties(captchaProperties);
        captchaService.setCodeGenerator(codeGenerator);
        captchaService.setCaptchaFont(captchaFont);
        return captchaService;
    }
}
